import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { useAppStore } from '@/stores/appStore';
import { Package, CheckCircle2, FileCode, Hash } from 'lucide-react';

interface ABIElement {
  id: string;
  name: string;
  type: string;
  value: string;
  index: number;
  encoded?: string;
}

export function Stage3ABIEncoding() {
  const { zkProofData, experienceMode } = useAppStore();
  const [isEncoding, setIsEncoding] = useState(false);
  const [currentElement, setCurrentElement] = useState(-1);
  const [encodingProgress, setEncodingProgress] = useState(0);
  const [finalCalldata, setFinalCalldata] = useState('');
  
  const [elements, setElements] = useState<ABIElement[]>([]);
  
  // Update elements when zkProofData changes - 使用标准算法
  useEffect(() => {
    const createABIElements = async (): Promise<ABIElement[]> => {
      console.log('\n=== 📦 Stage3: 开始创建标准ABI元素 ===');
      
      if (!zkProofData?.proof) {
        console.log('❌ 没有proof数据，使用mock数据');
        return createMockElements();
      }
      
      try {
        console.log('步骤3.1: 使用标准PLONK proof提取算法');
        
        // 使用标准提取算法（与pack_proof_abi_standard.js完全一致）
        const { extractProofElements } = await import('@/utils/abiEncoder');
        const proofValues = extractProofElements(zkProofData.proof);
        
        console.log('步骤3.2: 转换为ABI元素格式');
        const elements: ABIElement[] = [];
        
        // 创建标准的24个元素
        proofValues.forEach((value, index) => {
          // 确定元素类型和名称
          let name: string;
          let id: string;
          
          if (index < 18) {
            // G1点坐标 (9个点 × 2坐标)
            const pointIndex = Math.floor(index / 2);
            const coord = index % 2 === 0 ? 'x' : 'y';
            const pointNames = ['A', 'B', 'C', 'Z', 'T1', 'T2', 'T3', 'Wxi', 'Wxiw'];
            name = `${pointNames[pointIndex]}.${coord}`;
            id = `g1_${pointIndex}_${coord}`;
          } else {
            // 标量字段 (6个评估值)
            const scalarIndex = index - 18;
            const scalarNames = ['eval_a', 'eval_b', 'eval_c', 'eval_s1', 'eval_s2', 'eval_zw'];
            name = scalarNames[scalarIndex] || `eval_${scalarIndex}`;
            id = `scalar_${scalarIndex}`;
          }
          
          elements.push({
            id,
            name,
            type: 'uint256',
            value: value, // 已经是字符串格式
            index
          });
        });
        
        console.log(`✅ 步骤3.2完成: 创建了${elements.length}个标准ABI元素`);
        console.log('=== 📦 Stage3: ABI元素创建完成 ===\n');
        
        return elements;
        
      } catch (error) {
        console.error('❌ 标准提取失败，使用mock数据:', error);
        return createMockElements();
      }
    };
    
    // Mock数据生成函数
    const createMockElements = (): ABIElement[] => {
      const elements: ABIElement[] = [];
      
      // 生成标准的24个mock元素
      for (let i = 0; i < 24; i++) {
        let name: string;
        let id: string;
        
        if (i < 18) {
          const pointIndex = Math.floor(i / 2);
          const coord = i % 2 === 0 ? 'x' : 'y';
          const pointNames = ['A', 'B', 'C', 'Z', 'T1', 'T2', 'T3', 'Wxi', 'Wxiw'];
          name = `${pointNames[pointIndex]}.${coord} [mock]`;
          id = `mock_g1_${pointIndex}_${coord}`;
        } else {
          const scalarIndex = i - 18;
          const scalarNames = ['eval_a', 'eval_b', 'eval_c', 'eval_s1', 'eval_s2', 'eval_zw'];
          name = `${scalarNames[scalarIndex]} [mock]`;
          id = `mock_scalar_${scalarIndex}`;
        }
        
        elements.push({
          id,
          name,
          type: 'uint256',
          value: (BigInt(123456) * BigInt(i + 1)).toString(),
          index: i
        });
      }
      
      return elements;
    };
    
    // 异步函数调用
    createABIElements().then(setElements);
  }, [zkProofData]);
  
  // Public data hash
  const dataHash = zkProofData?.public?.[0] || "21684337208779804888941250689604787706765813346243268687471433053195528470185";
  
  useEffect(() => {
    if (experienceMode.autoplay) {
      const timer = setTimeout(() => {
        startEncoding();
      }, 2000);
      
      return () => clearTimeout(timer);
    }
  }, [experienceMode.autoplay]);
  
  const startEncoding = async () => {
    console.log('\n=== 📦 STAGE 3: 开始ABI编码 ===');
    console.log('步骤3.1: 检查是否已在编码中');
    
    if (isEncoding) {
      console.log('❌ 步骤3.1失败: ABI编码已在进行中');
      return;
    }
    
    console.log('步骤3.2: 初始化编码状态');
    setIsEncoding(true);
    setEncodingProgress(0);
    console.log('  - 编码状态: 已启动');
    console.log('  - 进度重置: 0%');
    console.log('  - 元素总数:', elements.length);
    console.log('  - dataHash:', dataHash);
    
    // Encode each element
    console.log('\n步骤3.3: 开始逐个编码证明元素');
    for (let i = 0; i < elements.length; i++) {
      const element = elements[i];
      console.log(`\n--- 编码元素 ${i+1}/${elements.length}: ${element.name} ---`);
      console.log('  - 元素ID:', element.id);
      console.log('  - 类型:', element.type);
      console.log('  - 原始值:', element.value);
      
      setCurrentElement(i);
      
      // Simulate encoding process
      console.log('  - 开始模拟编码过程...');
      for (let progress = 0; progress <= 100; progress += 10) {
        const totalProgress = (i / elements.length * 100) + (progress / elements.length);
        setEncodingProgress(totalProgress);
        await new Promise(resolve => setTimeout(resolve, 50));
        
        if (progress % 50 === 0) {
          console.log(`    编码进度: ${progress}% (总体: ${totalProgress.toFixed(1)}%)`);
        }
      }
      
      // Mark element as encoded
      console.log('  - 生成编码结果...');
      setElements(prev => prev.map((el, index) => {
        if (index === i) {
          const value = String(el.value || '');
          const hexValue = value.startsWith('0x') ? value.slice(2) : value;
          const encoded = hexValue.padStart(64, '0');
          console.log(`  - 编码结果: 0x${encoded}`);
          return { ...el, encoded };
        }
        return el;
      }));
      
      console.log(`✅ 元素 ${element.name} 编码完成`);
      await new Promise(resolve => setTimeout(resolve, 200));
    }
    
    // Generate final calldata using standard ABI encoding
    console.log('\n步骤3.4: 使用标准ABI编码生成最终调用数据');
    
    try {
      console.log('  - 导入标准ABI编码器...');
      const { encodeProofForWeBASE } = await import('@/utils/abiEncoder');
      
      console.log('  - 执行标准编码（abi.encode(uint256[24], uint256)）...');
      const finalData = encodeProofForWeBASE({
        proof: zkProofData?.proof,
        input: { dataHash },
        public: [dataHash]
      });
      
      console.log('✅ 标准ABI编码完成');
      console.log('  - 最终调用数据长度:', finalData.length, '字符');
      console.log('  - 预期长度: 1602字符 (800字节 + 0x前缀)');
      console.log('  - 最终调用数据预览:', finalData.slice(0, 100) + '...');
      console.log('  - 编码格式: abi.encode(uint256[24], uint256)');
      
      setFinalCalldata(finalData);
      
    } catch (error) {
      console.error('❌ 标准ABI编码失败，使用简化编码:', error);
      
      // 回退到简化编码（仅用于演示）
      console.log('  - 使用简化编码作为回退...');
      const encodedData = elements.map(el => {
        const value = typeof el.value === 'string' ? el.value : String(el.value);
        try {
          const bigintValue = BigInt(value);
          return bigintValue.toString(16).padStart(64, '0');
        } catch {
          return '0'.padStart(64, '0');
        }
      }).join('');
      
      const dataHashHex = BigInt(dataHash).toString(16).padStart(64, '0');
      const finalData = `0x${encodedData}${dataHashHex}`;
      
      console.log('  - 简化编码完成，长度:', finalData.length, '字符');
      setFinalCalldata(finalData);
    }
    
    console.log('\n步骤3.5: 完成编码过程');
    setCurrentElement(-1);
    setIsEncoding(false);
    setEncodingProgress(100);
    
    console.log('🎉 Stage3完成: ABI编码生成800字节调用数据');
    console.log('=== 📦 STAGE 3: 结束 ===\n');
  };
  
  const getElementColor = (index: number) => {
    if (index < currentElement) return 'border-crypto-green bg-crypto-green/10';
    if (index === currentElement) return 'border-quantum-blue bg-quantum-blue/10';
    return 'border-gray-600 bg-gray-700/30';
  };
  
  return (
    <div className="stage-container">
      <div className="max-w-6xl mx-auto w-full">
        {/* Stage title */}
        <motion.div
          initial={{ opacity: 0, y: -50 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.8 }}
          className="text-center mb-12"
        >
          <h1 className="text-5xl font-bold gradient-text mb-4">
            📦 ABI编码工厂
          </h1>
          <p className="text-xl text-gray-300">
            将证明数据转换为区块链标准格式
          </p>
        </motion.div>
        
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 w-full">
          {/* Left side - Encoding visualization */}
          <motion.div
            initial={{ opacity: 0, x: -100 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 0.4, duration: 0.8 }}
            className="space-y-6"
          >
            {/* Encoding machine */}
            <div className="floating-card">
              <h3 className="text-2xl font-semibold text-white mb-6 flex items-center">
                <Package className="mr-3 text-quantum-blue" size={28} />
                ABI编码器
              </h3>
              
              {/* Encoding visualization */}
              <div className="relative h-80 bg-slate-800 rounded-lg p-6 overflow-hidden">
                {/* Input funnel */}
                <div className="absolute top-4 left-4">
                  <motion.div
                    className="w-16 h-16 border-4 border-quantum-blue rounded-lg flex items-center justify-center"
                    animate={isEncoding ? { 
                      scale: [1, 1.1, 1],
                      borderColor: ['#3b82f6', '#10b981', '#3b82f6']
                    } : {}}
                    transition={{ duration: 1, repeat: isEncoding ? Infinity : 0 }}
                  >
                    <FileCode className="w-8 h-8 text-quantum-blue" />
                  </motion.div>
                  <p className="text-xs text-center mt-2 text-gray-300">proof.json</p>
                </div>
                
                {/* Processing pipeline */}
                <div className="absolute top-20 left-4 right-4">
                  <motion.div
                    className="h-2 bg-gray-600 rounded-full overflow-hidden"
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                  >
                    <motion.div
                      className="h-full bg-gradient-to-r from-quantum-blue to-crypto-green"
                      animate={{ width: `${encodingProgress}%` }}
                      transition={{ duration: 0.3 }}
                    />
                  </motion.div>
                  
                  {/* Data flow particles */}
                  {isEncoding && (
                    <>
                      {Array.from({ length: 6 }, (_, i) => (
                        <motion.div
                          key={i}
                          className="absolute w-3 h-3 bg-quantum-blue rounded-full"
                          style={{ left: '0%', top: '-4px' }}
                          animate={{
                            x: [0, 400],
                            opacity: [0, 1, 1, 0],
                            scale: [0.5, 1, 0.5],
                          }}
                          transition={{
                            duration: 2,
                            delay: i * 0.3,
                            repeat: Infinity,
                          }}
                        />
                      ))}
                    </>
                  )}
                </div>
                
                {/* Encoding units */}
                <div className="absolute top-32 left-4 right-4 bottom-20">
                  <div className="grid grid-cols-6 gap-2 h-full">
                    {Array.from({ length: 24 }, (_, i) => (
                      <motion.div
                        key={i}
                        className={`rounded border-2 flex items-center justify-center text-xs font-mono transition-all ${
                          i <= currentElement 
                            ? 'border-crypto-green bg-crypto-green/20 text-crypto-green'
                            : i === currentElement + 1 && isEncoding
                            ? 'border-quantum-blue bg-quantum-blue/20 text-quantum-blue'
                            : 'border-gray-600 bg-gray-700/50 text-gray-400'
                        }`}
                        animate={i === currentElement ? {
                          scale: [1, 1.1, 1],
                          opacity: [0.7, 1, 0.7]
                        } : {}}
                        transition={{ duration: 0.5, repeat: i === currentElement ? Infinity : 0 }}
                      >
                        {i < 18 ? `G${Math.floor(i/2)+1}` : `E${i-17}`}
                      </motion.div>
                    ))}
                  </div>
                </div>
                
                {/* Output */}
                <div className="absolute bottom-4 right-4">
                  <motion.div
                    className="w-16 h-16 border-4 border-crypto-green rounded-lg flex items-center justify-center"
                    animate={finalCalldata ? { 
                      scale: [1, 1.2, 1],
                      boxShadow: [
                        '0 0 0 rgba(16, 185, 129, 0)',
                        '0 0 20px rgba(16, 185, 129, 0.6)',
                        '0 0 0 rgba(16, 185, 129, 0)'
                      ]
                    } : {}}
                    transition={{ duration: 1, repeat: finalCalldata ? 3 : 0 }}
                  >
                    <Hash className="w-8 h-8 text-crypto-green" />
                  </motion.div>
                  <p className="text-xs text-center mt-2 text-gray-300">800字节</p>
                </div>
              </div>
              
              {/* Control panel */}
              <div className="mt-6">
                <motion.button
                  onClick={startEncoding}
                  disabled={isEncoding}
                  whileHover={{ scale: isEncoding ? 1 : 1.02 }}
                  whileTap={{ scale: isEncoding ? 1 : 0.98 }}
                  className={`w-full py-3 px-6 rounded-lg font-semibold transition-all ${
                    isEncoding 
                      ? 'bg-gray-700 text-gray-500 cursor-not-allowed'
                      : 'bg-quantum-blue hover:bg-blue-600 text-white'
                  }`}
                >
                  {isEncoding ? (
                    <span className="flex items-center justify-center">
                      <motion.div
                        animate={{ rotate: 360 }}
                        transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
                        className="w-5 h-5 border-2 border-white border-t-transparent rounded-full mr-2"
                      />
                      正在编码... {encodingProgress.toFixed(0)}%
                    </span>
                  ) : (
                    '🚀 开始ABI编码'
                  )}
                </motion.button>
              </div>
            </div>
            
            {/* Data structure info */}
            <div className="floating-card">
              <h3 className="text-lg font-semibold text-white mb-4">📋 数据结构</h3>
              <div className="space-y-3 text-sm">
                <div className="flex justify-between items-center p-2 bg-slate-800 rounded">
                  <span className="text-gray-300">G1群元素 (9个点)</span>
                  <span className="text-blue-400">18 × uint256</span>
                </div>
                <div className="flex justify-between items-center p-2 bg-slate-800 rounded">
                  <span className="text-gray-300">评估标量 (6个)</span>
                  <span className="text-purple-400">6 × uint256</span>
                </div>
                <div className="flex justify-between items-center p-2 bg-slate-800 rounded">
                  <span className="text-gray-300">数据哈希 (1个)</span>
                  <span className="text-green-400">1 × uint256</span>
                </div>
                <div className="border-t border-gray-600 pt-2">
                  <div className="flex justify-between items-center font-semibold">
                    <span className="text-white">总计</span>
                    <span className="text-gradient">25 × uint256 = 800字节</span>
                  </div>
                </div>
              </div>
            </div>
          </motion.div>
          
          {/* Right side - Element details */}
          <motion.div
            initial={{ opacity: 0, x: 100 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 0.6, duration: 0.8 }}
            className="space-y-6"
          >
            {/* Elements list */}
            <div className="floating-card max-h-96 overflow-y-auto">
              <h3 className="text-2xl font-semibold text-white mb-6">🔢 编码元素</h3>
              
              <div className="space-y-2">
                {elements.map((element, index) => (
                  <motion.div
                    key={element.id}
                    className={`p-3 rounded border transition-all ${getElementColor(index)}`}
                    initial={{ opacity: 0, x: 20 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ delay: index * 0.02 }}
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex items-center space-x-3">
                        <span className="text-xs bg-gray-600 px-2 py-1 rounded font-mono">
                          [{index}]
                        </span>
                        <span className="font-medium text-white">
                          {element.name}
                        </span>
                      </div>
                      
                      {index < currentElement ? (
                        <CheckCircle2 className="w-5 h-5 text-crypto-green" />
                      ) : index === currentElement ? (
                        <motion.div
                          animate={{ rotate: 360 }}
                          transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
                          className="w-5 h-5 border-2 border-quantum-blue border-t-transparent rounded-full"
                        />
                      ) : null}
                    </div>
                    
                    <div className="mt-2 text-xs font-mono text-gray-400">
                      {String(element.value || '').slice(0, 20)}...{String(element.value || '').slice(-6)}
                    </div>
                    
                    {element.encoded && (
                      <motion.div
                        initial={{ opacity: 0, height: 0 }}
                        animate={{ opacity: 1, height: 'auto' }}
                        className="mt-2 text-xs font-mono text-crypto-green bg-crypto-green/10 p-2 rounded"
                      >
                        ✓ 已编码: {String(element.encoded || '').slice(0, 16)}...
                      </motion.div>
                    )}
                  </motion.div>
                ))}
                
                {/* Data hash element */}
                <motion.div
                  className={`p-3 rounded border ${
                    encodingProgress === 100 
                      ? 'border-crypto-green bg-crypto-green/10'
                      : 'border-gray-600 bg-gray-700/30'
                  }`}
                  initial={{ opacity: 0, x: 20 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: elements.length * 0.02 }}
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-3">
                      <span className="text-xs bg-gray-600 px-2 py-1 rounded font-mono">
                        [24]
                      </span>
                      <span className="font-medium text-white">
                        dataHash
                      </span>
                    </div>
                    
                    {encodingProgress === 100 && (
                      <CheckCircle2 className="w-5 h-5 text-crypto-green" />
                    )}
                  </div>
                  
                  <div className="mt-2 text-xs font-mono text-gray-400">
                    {String(dataHash || '').slice(0, 20)}...{String(dataHash || '').slice(-6)}
                  </div>
                </motion.div>
              </div>
            </div>
            
            {/* Final output */}
            {finalCalldata && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                className="floating-card"
              >
                <h3 className="text-lg font-semibold text-white mb-4 flex items-center">
                  <Hash className="mr-2 text-crypto-green" size={20} />
                  🎉 编码完成
                </h3>
                
                <div className="bg-slate-800 rounded-lg p-4">
                  <div className="text-sm text-gray-300 mb-2">最终calldata (800字节):</div>
                  <div className="text-xs font-mono text-crypto-green break-all">
                    {String(finalCalldata || '').slice(0, 100)}...
                    <br />
                    ...{String(finalCalldata || '').slice(-100)}
                  </div>
                </div>
                
                <div className="mt-4 grid grid-cols-2 gap-4 text-sm">
                  <div className="bg-slate-700 rounded p-3 text-center">
                    <div className="text-2xl mb-1">📊</div>
                    <div className="text-gray-300">数据大小</div>
                    <div className="text-white font-semibold">800 bytes</div>
                  </div>
                  <div className="bg-slate-700 rounded p-3 text-center">
                    <div className="text-2xl mb-1">🔢</div>
                    <div className="text-gray-300">参数数量</div>
                    <div className="text-white font-semibold">25 uint256</div>
                  </div>
                </div>
                
                <motion.div
                  className="mt-4 text-center text-quantum-blue"
                  animate={{ y: [0, -10, 0] }}
                  transition={{ duration: 2, repeat: Infinity }}
                >
                  <span className="text-2xl">🚀</span>
                  <p className="font-semibold">准备发送到区块链...</p>
                </motion.div>
              </motion.div>
            )}
            
            {/* Technical details */}
            {experienceMode.showTechDetails && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 1 }}
                className="bg-slate-800/50 rounded-lg p-4 border border-slate-700"
              >
                <h4 className="text-lg font-semibold text-white mb-3">🔧 ABI编码细节</h4>
                <div className="space-y-2 text-sm text-gray-300">
                  <p>• <strong>标准格式：</strong>abi.encode(uint256[24], uint256)</p>
                  <p>• <strong>字节对齐：</strong>每个uint256占用32字节</p>
                  <p>• <strong>大端序：</strong>高位字节在前的编码方式</p>
                  <p>• <strong>兼容性：</strong>符合智能合约标准</p>
                </div>
              </motion.div>
            )}
          </motion.div>
        </div>
      </div>
    </div>
  );
}